$(function() {
    let userInfoObj = {};
    let index = 0;
    let pageNumber;
    let init = () => {
        initEvent()
        initData()
    }
    let initEvent = () => {
        $('#showAddDialogBtn').on('click', onShowAddDialogBtnClick)
        $('#showUpdateDialogBtn').on('click', onShowUpdateDialogBtnClick)
        $('#changeBtn').on('click', onSaveBtnClick)
        $('table').on('click', '[type="checkbox"]', onCheckboxClick)
        $('.close-btn').on('click', () => {
            $('#reset').trigger('click')
            $('form img')[0].src = ''
        })
        $('#clearUserBackLogin').on('click', function() {
            localStorage.clear('*')
            location.replace('/login')
        })
        $('#showDelDialogBtn').on('click', onShowDelDialogBtnClick)
        $('#searchUser').on('keyup', onSearchUsers)
        $('#closeUser').on('click', confirmDelBtn)
        $('#userListPage').on('click', 'li', function() {
            $(this).addClass('on').siblings().removeClass('on')
            index = $(this).index()
            initData(null, page = index)
        })
        $('#userListPagePrev').on('click', function() {
            index--
            index = index < 0 ? pageNumber - 1 : index
            initData(null, page = index)
        })
        $('#userListPageNext').on('click', function() {
            index++
            index = index > pageNumber - 1 ? 0 : index
            initData(null, page = index)
        })
    }
    let confirmDelBtn = async function() {
        let str = $('tbody').find('[type="checkbox"]:checked').get().map(item => item.id).join(',')
        let delStatus = await delUser(
            data = {
                ids: str
            }
        ).catch(err => {
            alert(err)
            return;
        })
        $('#myDelModal').modal('hide')
        initData()
    }
    let onSearchUsers = function() {
        let query = this.value
        initData(query)
    }
    let onShowDelDialogBtnClick = function() {
        $('#myDelModal').modal({
            show: true,
            backdrop: 'static'
        })
    }
    let onCheckboxClick = function() {
            let len = $('tbody').find('[type="checkbox"]').length
            let checkLen = $('tbody [type="checkbox"]:checked').length
            if ($(this).hasClass('check-all')) {
                $('tbody [type="checkbox"]').prop('checked', this.checked)
                checkLen = $('tbody [type="checkbox"]:checked').length
            } else {
                $('thead [type="checkbox"]').prop('checked', len == checkLen);
            }
            $('#showDelDialogBtn').prop('disabled', !checkLen)
            $('#showUpdateDialogBtn').prop('disabled', checkLen !== 1)
        }
        //修改显示对话框
    let onShowUpdateDialogBtnClick = function() {
            let userInfo = userInfoObj[$('tbody [type="checkbox"]:checked')[0].id];
            $('.modal-title').html('修改用户');
            $('#changeBtn').html('确认修改');
            $('#myModal').modal({
                show: true,
                backdrop: 'static'
            })
            $('#name').val(userInfo.name)
            $('#age').val(userInfo.age)
            $('#edu').find(`option[value="${userInfo.edu}"]`).prop('selected', true)
            $('#gender').find(`[value="${userInfo.gender}"]`).attr('checked', true)
            $('#hobbies').find('[type="checkbox"]').prop('checked', false)
            userInfo.hobbies.split('-').forEach((item, index) => {
                $('#hobbies').find(`[type="checkbox"][value="${item}"]`).prop('checked', true)
            })
            $('[type="file"]').siblings('img').attr('src', userInfo.avatar).css("z-index", 1)
        }
        // 增加显示对话框
    let onShowAddDialogBtnClick = function() {
            $('.modal-title').html('增加用户');
            $('#changeBtn').html('确认增加');
            new UploadToken({
                $el: $('[type=file]'),
                callback(url) {
                    $('[type=file]').siblings('img')
                        .attr('src', url)
                        .css('zIndex', 1)
                    $('[type=file]').siblings('.glyphicon-plus') && $('[type=file]').siblings('.glyphicon-plus')
                        .css('zIndex', -1)
                }
            });
            $('#myModal').modal({
                show: true,
                backdrop: 'static'
            })
        }
        // 存储用户信息
    let onSaveBtnClick = function() {
        let obj = {}
        let arr = []
            /* TODOS   表单验证 */
        $('#myModal').find('input:not([type="checkbox"]):not([type="reset"])').add($('select')).each((index, item) => {
            if (item.id) {
                obj[item.id] = item.value
                if (item.id === 'avatar') {
                    obj[item.id] = $(item).siblings('img')[0].src;
                }
            } else {
                if (item.checked) {
                    obj[item.name] = item.value;
                }
            }
        })
        $('input[name="hobbies"]').each((index, item) => {
            if (item.checked) {
                arr.push(item.value)
            }
        })
        obj['hobbies'] = arr.join('-')
        if ($('tbody  [type="checkbox"]:checked').length && $(this).html() === "确认修改") {
            obj['id'] = $('tbody  [type="checkbox"]:checked')[0].id
        }
        saveUser(obj);
    }
    async function saveUser(data) {
        let saveUserLists = await suLists(
            data
        ).catch(err => {
            alert(err)
            return;
        })
        $('#reset').trigger('click')
        $('form img')[0].src = ''
        $('#myModal').modal('hide')
        initData()
    }
    let initData = async(query = null, page = null) => {
        let renderLists = await renderUser(
            data = {
                query: query,
                page: page
            }
        ).catch(err => {
            alert(err)
            return
        })
        renderTable(renderLists)
    }
    let renderTable = (res) => {
        userInfoObj = {};
        let eduArr = [null, null, '小学', '中学', '大学'];
        let obj = {
            1: '抽烟',
            2: "喝酒",
            3: "烫头"
        }
        pageNumber = Math.ceil(res.total / 4)
        renderNavList(pageNumber)
        res.userObj.forEach(item => {
            userInfoObj[item._id] = JSON.stringify(item);
            item.hobbies = item.hobbies.split('-').map(item => obj[item]).join('-')
            item.edu = eduArr[item.edu]
        })
        $('tbody').html(template('tableWrapper', res))
        $('#imgWrapper').html(template('imgList', res))
        for (let o in userInfoObj) {
            userInfoObj[o] = JSON.parse(userInfoObj[o])
        }
    }
    let renderNavList = function(pageNumber) {
        let arr = []
        for (let i = 1; i <= pageNumber; i++) {
            arr.push(`
            <li id="${i}" class='${i===index+1?'on':''}'>${i}</li>
            `)
        }
        $('#userListPage').html(arr.join(''))
    }
    init()
})